package com.nf.health.app.activity.home;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.RegisterRecordActivity;
import com.nf.health.app.adapter.SearchNewDoctorAdapter;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.customview.DividerListItemDecoration;
import com.nf.health.app.http.Act;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;
import com.nf.health.app.models.SearchMainDocBean;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SearchNewDoctorActivity extends BaseActivity {
    public static String HID = "com.nf.SearchNewDoctorActivity.hid";
    @Bind(R.id.et_main_search)
    EditText mEtMainSearch;
    @Bind(R.id.titlebar_right_view_sraech)
    ImageView titlebar_right_view_sraech;
    @Bind(R.id.recycler)
    LRecyclerView mRecyclerView;
    private InputMethodManager mInputManager;
    private LRecyclerViewAdapter mRecyclerViewAdapter;
    private int mPageSize = 10;
    private int mPageNo = 1;
    private int mTotalCount;
    private int mCurrentCount;
    private boolean isRefresh = false;
    private List<SearchMainDocBean> mList = new ArrayList<>();
    private String mSearchContent = "";
    private boolean isLodaingMore = false;
    private String from = ""; //标记是从哪里传过来的
    public static String  ShowRightButtonFlag= "is.show.right.button";
    private boolean ShowRightButton = false;
    private String hid = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.include_newsearch);
        setContent(R.layout.activity_newmainsearchdocactivity);
        ButterKnife.bind(this);
        initView();
        initListener();
    }
    private void initView() {
        hid = getIntent().getStringExtra(HID);
        from = getIntent().getStringExtra(Constants.FROM);
        ShowRightButton = getIntent().getBooleanExtra(ShowRightButtonFlag,false);
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        SearchNewDoctorAdapter mAdapter =  new SearchNewDoctorAdapter(this,mList);
        mRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.addItemDecoration(new DividerListItemDecoration(this, LinearLayoutManager.VERTICAL));
        mRecyclerView.setAdapter(mRecyclerViewAdapter);
        initData(mSearchContent);

        titlebar_right_view_sraech.setImageResource(R.drawable.fast_inquiry_icon);
        if(ShowRightButton){
            titlebar_right_view_sraech.setVisibility(View.VISIBLE);
        }else{
            titlebar_right_view_sraech.setVisibility(View.GONE);
        }
    }
    private void initListener() {
        titlebar_right_view_sraech.setOnClickListener(this);
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
                if(state == LoadingFooter.State.Loading) {
                    return;
                }
                mPageNo++;
                if(mCurrentCount < mTotalCount) {
                    // loading more
                    isLodaingMore = true;
                    RecyclerViewStateUtils.setFooterViewState(SearchNewDoctorActivity.this, mRecyclerView, 10, LoadingFooter.State.Loading, null);
                    initData(mSearchContent);

                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(SearchNewDoctorActivity.this, mRecyclerView, 10, LoadingFooter.State.TheEnd, null);

                }
            }
        });

        mRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
              /*  Intent intent = new Intent(SearchNewDoctorActivity.this, DoctorDetailsActivity.class);
                intent.putExtra(Constants.DOCTOR_ID,mList.get(position).getDoctorid());
                intent.putExtra(Constants.FROM,from);
                startActivity(intent);*/
                Bundle docDetailBundle = new Bundle();
                docDetailBundle.putString(DocDetailActivity.DOCTORID, mList.get(position).getDoctorid());
                ActivityUtils.showActivity(SearchNewDoctorActivity.this, DocDetailActivity.class, docDetailBundle);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        mEtMainSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSearchContent = s.toString();
                mPageNo = 1;
                initData(mSearchContent);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    private void initData(String searchContent) {
        provider.queryDoctorBySomeWay1(searchContent,mPageNo+"",mPageSize+"",hid);
    }



    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.ll_search_ks:

                break;
            case R.id.titlebar_right_view_sraech:
                ActivityUtils.showActivity(this, RegisterRecordActivity.class);
                break;
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        mTotalCount = Integer.parseInt(JsonUtils.getFiledData(object + "", "totalCount"));

        RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
        if(Act.Flag.SEARCH_DOCTOR_KESHI_HOSTIPAL_FLG.equals(actionName)){
            //返回问诊bean类集合
            String data = JsonUtils.getFiledData(object+"", "data");
            String list = JsonUtils.getFiledData(data, "list");
            Gson gson = new MyGsonBuilder().createGson();
            List<SearchMainDocBean> mNewList = gson.fromJson(list, new TypeToken<List<SearchMainDocBean>>() {}.getType());
            if(isLodaingMore){
                mList.addAll(mNewList);
                isLodaingMore = false;
            }else{
                mList.clear();
                mList.addAll(mNewList);
            }
            mCurrentCount = mList.size();
            mRecyclerViewAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
    }

    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                mInputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    private void refreshCompleted(){
        isRefresh = false;
        mRecyclerView.refreshComplete();
    }
}
